package com.zhidao.backend.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhidao.backend.common.StatusCode;
import com.zhidao.backend.entity.Collect;
import com.zhidao.backend.exception.BusinessException;
import com.zhidao.backend.mapper.CollectMapper;
import com.zhidao.backend.service.ICollectService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {

    @Override
    public void collect(Long userId, Long routeId) {
        Collect collect = new Collect();
        collect.setUserId(userId);
        collect.setRouteId(routeId);
        collect.setDeleted(false);
        if (!this.save(collect)) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "收藏失败");
        }
    }

    @Override
    public void cancelCollect(Long userId, Long routeId) {
        int res = baseMapper.delete(new QueryWrapper<Collect>().eq("user_id", userId).eq("route_id", routeId));
        if (res < 1) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "取消收藏失败");
        }
    }

    @Override
    public List<Long> getCollectRoutes(Long id) {
        List<Collect> collects = this.list(new QueryWrapper<Collect>().eq("user_id", id));
        return collects.stream().map(Collect::getRouteId).collect(Collectors.toList());
    }

    @Override
    public Boolean isCollect(Long userId, Long routeId) {
        Collect collect = this.getOne(new QueryWrapper<Collect>().eq("user_id", userId).eq("route_id", routeId));
        return collect != null;
    }
}
